﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ReverseOrderOfWordsInSentence
{
    class Program
    {
        static int counter = 0;
        const string wordPattern = @"\b(\w+)\b";
        static StringBuilder sentencePattern = new StringBuilder();

        static int CountWordsInSentence(string sentence)
        {
            Regex regex = new Regex(wordPattern);
            MatchCollection matches = regex.Matches(sentence);

            return matches.Count;
        }

        static string PutTheWordAtTheEnd(Match match)
        {
            string word = match.Value;
            if (Regex.IsMatch(word, wordPattern))
            {
                counter--;
                sentencePattern.Append(@"(\w+)");
                return string.Format("${0}", counter);
            }
            else
            {
                if (word != string.Empty)
                {
                    if (Char.IsPunctuation(word[0]))
                    {
                        sentencePattern.Append(string.Format(@"\{0}",word[0]));
                    }
                    else
                    {
                        sentencePattern.Append(@"\s+");
                    }
                }
                return word;
            }
        }

        public static string CapitalizeSentence(string sentence)
        {
            if (string.IsNullOrEmpty(sentence) == false)
            {
                string result = sentence.ToLower().TrimStart();
                result = Char.ToUpper(result[0]) + result.Substring(1);
                return result;
            }
            else
            {
                throw new ArgumentException("Sentence argument is null or empty.");
            }
        }

        public class Example
        {
            public static void Main()
            {
                string input = "A lass is picking, berries.";
                string pattern = @"(\w+)|(\s+)|,|\.|\?|\!|:";
                counter = CountWordsInSentence(input);
                counter++;
                
                string reverseWords=string.Empty;
                reverseWords+= Regex.Replace(input, pattern, new MatchEvaluator(PutTheWordAtTheEnd));

                string replacingPatter = sentencePattern.ToString();
                Regex regex = new Regex(replacingPatter);

                Console.WriteLine(regex.Match(input).Value);
                Console.WriteLine();
                string reversed = regex.Replace(input, reverseWords);
                reversed = CapitalizeSentence(reversed);
                Console.WriteLine(reversed);
                
                
            }
        }
    }
}
